<?php
namespace Ctrl;

use Lib;

use Model\HeroModel;
use Model\SeasonModel;
use Model\VersionModel;
use Lib\Paas\Login;

class Main extends Lib\Base\Ctrl
{
    private $db;
    private $version;
    private $seasonModel;
    private $versionModel;
    public function __construct()
    {
        //校验管理员权限
        $roleService = new Lib\Paas\Role();
        $checkAdmin = $roleService->getRoleInfo();
//        if ($checkAdmin['role'] != ROLE_ID) {
//            die('抱歉！您没有访问权限');
//        }
//        if (!in_array(MODULE_ID, $checkAdmin['moduleID']) ) {
//            die('抱歉！您没有访问权限');
//        }
        $this->db = Lib\Db\DbModel::init();
        //获取当前版本
        $this->version = $this->db->table('tbversion')->where(['isCurrent'=>1])->find('id');
        /*if (empty($this->version)){
            header("Location: ". U('dataImport/main'));
        }*/
        //实例化Login类
        $this->login = new Login();
        $this->assign('iActId', '1001');
        $this->seasonModel = new SeasonModel();
        $this->versionModel = new VersionModel();
    }

    /**
     * 数据导入视图
     */
    public function index()
    {
        //获取用户信息
        $login = new Lib\Paas\Login();
        $loginInfo = $login->getLoginInfo();
        $this->assign("adminName", $loginInfo['name']);
        if (DB_HOST['db_name'] == 'dbLRLibTest_xiangangwei') {
            $hostName = '当前是测试环境';
        } else {
            $hostName = '';
        }
        $this->assign('hostName', $hostName);
        $this->display('Admin/Main/index');
    }

    public function main()
    {



       //获取当前版本和季度信息
        $resVersion = $this->versionModel->getCurrentVersion();
        $resSeason = $this->seasonModel->getCurrentSeason();

        //获取可切换的版本号和季度
        $resVersionTotal = $this->versionModel->getChangeVersions();
        $resSeasonTotal = $this->seasonModel->getChangeSeasons();




        $this->assign("versionNumber", $resVersion['versionNumber']);
        $this->assign("seasonNumber", $resSeason['seasonNumber']);

        $this->assign('resVersionTotal', $resVersionTotal);
        $this->assign('resSeasonTotal', $resSeasonTotal);

        $saveDir = date('YmdHis', time());
        $this->assign("saveDir", $saveDir);
        $this->display('Admin/Main/main');
    }


    //切换当前版本和季度
    public function switchData()
    {
        if (empty(I('post.versionId')) || empty(I('post.seasonId'))) {
            $this->ajaxError('数据为空');
        }


        $versionId = I('post.versionId');
        $seasonId = I('post.seasonId');
        try {
            $this->db->begin();
            //更新版本表
            $this->db->table('tbversion')->where(['id' => $versionId])->update([
                'isCurrent' => 1,
                'updateTime' => date('Y-m-d H:i:s', time()),
                'updateMan' => $this->login->getLoginInfo()['name']
            ]);
            $this->db->table('tbversion')->where(['id' => ['!=', $versionId]])->update([
                'isCurrent' => 0,
                'updateTime' => date('Y-m-d H:i:s', time()),
                'updateMan' => $this->login->getLoginInfo()['name']
            ]);

            //更新季度表

            $this->db->table('tbseason')->where(['id' => $seasonId])->update([
                'isCurrent' => 1,
                'updateTime' => date('Y-m-d H:i:s', time()),
                'updateMan' => $this->login->getLoginInfo()['name']
            ]);
            $this->db->table('tbseason')->where(['id' => ['!=', $seasonId]])->update([
                'isCurrent' => 0,
                'updateTime' => date('Y-m-d H:i:s', time()),
                'updateMan' => $this->login->getLoginInfo()['name']
            ]);

            $this->db->commit();
            $this->ajaxSuccess("切换成功");
        } catch (\Exception $e) {
            $this->db->rollBack();
            $this->ajaxError('切换失败');
        }
    }


    //复制当前版本和季度的数据
    public function copy()
    {
        if (empty(I('post.versionNumber')) || empty(I('post.seasonNumber'))) {
            $this->ajaxError('数据为空');
        }

        $versionNum= I('post.versionNumber');
        $seasonNum = I('post.seasonNumber');


        //验证版本号和季度格式
        if (empty($versionNum)) {
            $this->ajaxError('版本号不能为空');
        }
        if (empty($seasonNum)) {
            $this->ajaxError('季度号不能为空');
        }

        $checkVersion = $this->versionModel->pregVersion($versionNum);
        if ($checkVersion === false) {
            $this->ajaxError('不是一个正确的版本号');
        }

        $checkSeason = $this->seasonModel->pregSeason($seasonNum);
        if ($checkSeason === false) {
            $this->ajaxError('不是一个正确的季度号');
        }

        //检查是否已经存在
        $resultVersion = $this->versionModel->getVersionByNum($versionNum);
        $resultSeason = $this->seasonModel->getSeasonByNum($seasonNum);


        if (!empty($resultVersion) && !empty($resultSeason)) {
            $this->ajaxError('版本和季度都已存在');
        }

        //当前版本和季度
        $currentVersion = $this->versionModel->getCurrentVersion();
        $currentSeason= $this->seasonModel->getCurrentSeason();


        $time = date('Y-m-d H:i:s', time());
        $creater = $this->login->getLoginInfo()['name'];
        $where = [
            'versionId'=> $currentVersion['id'],
            'seasonId'=> $currentSeason['id'],
            'isDelete'=>0
        ];
        try {
            $this->db->begin();

            //1.新建版本或者季度

            if (empty($resultVersion)) {
                $newVersionId = $this->db->table('tbversion')->insert([
                    'versionNumber'=>$versionNum,
                    'createTime'=>$time,
                    'creater'=>$creater
                ]);
                logWrite(parent::LOG_TYPE_INSENT, $newVersionId, 'tbversion');
            } else {
                $newVersionId = $resultVersion['id'];
            }
            if (empty($resultSeason)) {
                $newSeasonId = $this->db->table('tbseason')->insert([
                    'seasonNumber'=>$seasonNum,
                    'createTime'=>$time,
                    'creater'=>$creater
                ]);
                logWrite(parent::LOG_TYPE_INSENT, $newSeasonId, 'tbseason');
            } else {
                $newSeasonId = $resultSeason['id'];
            }


            //2.种族信息

            $nowRace = $this->db->table('tbrace')->where($where)->select();

            foreach ($nowRace as &$val) {
                unset($val['updateMan']);
                unset($val['updateTime']);
                unset($val['deleteTime']);
                $val['creater'] = $creater;
                $val['createTime'] = $time;
                $val['versionId'] = $newVersionId;
                $val['seasonId'] = $newSeasonId;
            }
            if (!empty($nowRace)) {
                $flag = $this->db->table('tbrace')->insertAll($nowRace);
            }


            //3.职业信息
            $nowJob = $this->db->table('tbjob')->where($where)->select();
            foreach ($nowJob as &$val) {
                unset($val['updateMan']);
                unset($val['updateTime']);
                unset($val['deleteTime']);
                $val['creater'] = $creater;
                $val['createTime'] = $time;
                $val['versionId'] = $newVersionId;
                $val['seasonId'] = $newSeasonId;
            }
            if (!empty($nowJob)) {
                $flag = $this->db->table('tbjob')->insertAll($nowJob);
                logWrite(parent::LOG_TYPE_INSENT, $flag, 'tbjob');
            }

            //4.英雄信息
            $nowHero = $this->db->table('tbhero')->where($where)->select();
            foreach ($nowHero as &$val) {
                unset($val['updateMan']);
                unset($val['updateTime']);
                unset($val['deleteTime']);

                $val['creater'] = $creater;
                $val['createTime'] = $time;
                $val['versionId'] = $newVersionId;
                $val['seasonId'] = $newSeasonId;
            }
            if (!empty($nowHero)) {
                $flag = $this->db->table('tbhero')->insertAll($nowHero);
                logWrite(parent::LOG_TYPE_INSENT, $flag, 'tbhero');
            }
            //5.棋子信息
            $nowChess = $this->db->table('tbchess')->where($where)->select();
            foreach ($nowChess as &$val) {
                unset($val['updateMan']);
                unset($val['updateTime']);
                unset($val['deleteTime']);
                $val['creater'] = $creater;
                $val['createTime'] = $time;
                $val['versionId'] = $newVersionId;
                $val['seasonId'] = $newSeasonId;
            }
            if (!empty($nowChess)) {
                $flag = $this->db->table('tbchess')->insertAll($nowChess);
                logWrite(parent::LOG_TYPE_INSENT, $flag, 'tbchess');
            }

            //6.道具信息
            $nowEquip = $this->db->table('tbequip')->where($where)->select();
            foreach ($nowEquip as &$val) {
                unset($val['updateMan']);
                unset($val['updateTime']);
                unset($val['deleteTime']);
                $val['creater'] = $creater;
                $val['createTime'] = $time;
                $val['versionId'] = $newVersionId;
                $val['seasonId'] = $newSeasonId;
            }
            if (!empty($nowEquip)) {
                $flag = $this->db->table('tbequip')->insertAll($nowEquip);
                logWrite(parent::LOG_TYPE_INSENT, $flag, 'tbequip');
            }
            $this->db->commit();
            logWrite(parent::LOG_TYPE_INSENT, true, '复制数据成功');
            $this->ajaxSuccess("复制成功");
        } catch (\Exception $e) {
            $this->db->rollback();
            logWrite(parent::LOG_TYPE_INSENT, false, '复制数据失败');
            $this->ajaxError('复制失败');
        }
    }


    //给当前版本和季度导入数据
    public function insertJson()
    {
        ini_set('memory_limit', -1);
        ini_set('max_execution_time', 0);

        $dataType = I('dataType');

        $fileInfo = $_FILES["jsonFile"];

        $data = json_decode(file_get_contents($fileInfo["tmp_name"]), true);

        $types = [
            1=>'种族',
            2=>'职业',
            3=>'英雄',
            4=>'棋子',
            5=>'道具',
        ];
        if (!in_array($dataType, array_keys($types))) {
            $this->ajaxError('请选择数据类型');
        }


        $resVersion = $this->versionModel->getCurrentVersion();
        $resSeason = $this->seasonModel->getCurrentSeason();


        //字段对应
        //种族
        $race = [
            'raceId',
            'name',
            'traitId',
            'introduce',
            'alias',
            'level',
            'TFTID',
        ];
        //职业
        $job = [
            'jobId',
            'name',
            'traitId',
            'introduce',
            'alias',
            'level',
            'TFTID',
        ];
        //英雄
        $hero = [
            'heroId',
            'name',
            'typeId',
            'miniId',
            'star',
            'imagePath',
            'TFTID',
            'shape',
            'quality'

        ];
        //棋子
        $chess = [
            'chessId',
            'title',
            'name',
            'displayName',
            'raceIds',
            'jobIds',
            'price',
            'skillName',
            'skillType',
            'skillImage',
            'skillIntroduce',
            'skillDetail',
            'life',
            'magic',
            'armor',
            'spellBlock',
            'attack',
            'attackSpeed',
            'lifeMag',
            'attackMag',
            'attackRange',
            'crit',
            'synergies',
            'TFTID',
            'originalImage',
            'illustrate'
        ];
        //道具
        $equip = [
            'equipId',
            'type',
            'name',
            'effect',
            'keywords',
            'formula',
            'heroIds',
            'imagePath',
            'TFTID',

        ];


        //检查json数据

        foreach ($data as $item) {
            switch ($dataType) {
                case '1':
                    $check_keys = array_diff($race, array_keys($item));
                    break;
                case '2':
                    $check_keys = array_diff($job, array_keys($item));
                    break;
                case '3':
                    $check_keys = array_diff($hero, array_keys($item));
                    break;
                case '4':
                    $check_keys = array_diff($chess, array_keys($item));
                    break;
                case '5':
                    $check_keys = array_diff($equip, array_keys($item));
                    break;

            }
            //json数据错误
            if (!empty($check_keys)) {
                $this->ajaxError('json数据错误');
                break;
            }
        }



        $where = [
            'versionId' =>$resVersion['id'],
            'seasonId' =>$resSeason['id'],
        //    'isDelete'=>0
        ];

        //开启事务
        $this->db->begin();
        foreach ($data as $item) {
            switch ($dataType) {
                case '1':
                    $table = 'tbrace';
                    $where['raceId'] = $item['raceId'];
                    $item['level'] = json_encode($item['level']);
                    break;
                case '2':
                    $table = 'tbjob';
                    $where['jobId'] = $item['jobId'];
                    $item['level'] = json_encode($item['level']);
                    break;
                case '3':
                    $table = 'tbhero';
                    $where['heroId'] = $item['heroId'];
                    break;
                case '4':
                    $table = 'tbchess';
                    $where['chessId'] = $item['chessId'];
                    break;
                case '5':
                    $table = 'tbequip';
                    $where['equipId'] = $item['equipId'];
                    break;

            }

            //检查是否存在
            $old = $this->db->table($table)->where($where)->find();


            //更新
            if ($old) {
                $item['isDelete'] = 0;
                $item['updateMan'] = $this->login->getLoginInfo()['name'];
                $item['updateTime'] = date('Y-m-d H:i:s');


                $flag = $this->db->table($table)->where($where)->update($item);
            } else {
                $item['creater'] = $this->login->getLoginInfo()['name'];
                $item['createTime'] = date('Y-m-d H:i:s');
                //添加
                $insertData = array_merge($where, $item);
                $flag = $this->db->table($table)->insert($insertData);
            }

            if ($flag===false) {
                $this->db->rollback();
                logWrite(parent::LOG_TYPE_OTHER, false, '上传数据失败');
                $this->ajaxError("同步失败");
            }
        }
        $this->db->commit();
        logWrite(parent::LOG_TYPE_OTHER, true, '上传数据成功');
        $this->ajaxSuccess("同步成功");
    }


    //删除数据

    public function deleteData()
    {
        $dataType = I('post.dataType');
        $id = I('post.id');

        $types = [
            1=>'种族',
            2=>'职业',
            3=>'英雄',
            4=>'棋子',
            5=>'道具',
        ];

        if (!in_array($dataType, array_keys($types))) {
            $this->ajaxError('请选择数据类型');
        }

        $resVersion = $this->versionModel->getCurrentVersion();
        $resSeason = $this->seasonModel->getCurrentSeason();

        $where = [
            'versionId' =>$resVersion['id'],
            'seasonId' =>$resSeason['id'],
            'isDelete'=>0
        ];

        switch ($dataType) {
            case '1':
                $table = 'tbrace';
                if ($id) {
                    $where['raceId'] = $id;
                }
                break;
            case '2':
                $table = 'tbjob';
                if ($id) {
                    $where['jobId'] = $id;
                }

                break;
            case '3':
                $table = 'tbhero';
                if ($id) {
                    $where['heroId'] = $id;
                    ;
                }

                break;
            case '4':
                $table = 'tbchess';
                if ($id) {
                    $where['chessId'] = $id;
                }

                break;
            case '5':
                $table = 'tbequip';
                if ($id) {
                    $where['equipId'] = $id;
                }
                break;

        }

        $res = $this->db->table($table)->where($where)->update(['isDelete'=>1,'deleteTime'=>date('Y-m-d H:i:s'),'deleteMan'=>$this->login->getLoginInfo()['name']]);
        logWrite(parent::LOG_TYPE_DEL, $res, $table);

        if ($res) {
            $this->ajaxSuccess("删除成功");
        } else {
            $this->ajaxError('删除失败');
        }
    }


    //生成js
    public function makeJs()
    {
        $login = new Login();
        $name = $login->getLoginInfo()['name'];
        //当前版本和季度
        $currentVersion = $this->versionModel->getCurrentVersion();
        $currentSeason= $this->seasonModel->getCurrentSeason();

        $versionNumber = $currentVersion['versionNumber'];
        $seasonNumber = $currentSeason['seasonNumber'];
        $where = [
            'versionId'=> $currentVersion['id'],
            'seasonId'=> $currentSeason['id'],
            'isDelete'=>0
        ];

        //纪录到tbrecord
        $save['createtime'] = date("Y-m-d H:i:s", time());
        $save['versionId'] = $currentVersion['id'].'-'.$currentSeason['id'];
        $save['creater'] = $name;


        $path = $versionNumber.'-'.$seasonNumber;
        $dir = $this->makeJsDir($path);


        //种族
        $raceData = $this->db->table('tbrace')->where($where)->select();

        $raceFormat = [];
        foreach ($raceData as &$value) {
            $raceFormat[$value['raceId']] = $value['name'];
            $value['level'] = json_decode($value['level'], true);
            $value['imagePath'] = "https://game.gtimg.cn/images/lol/act/img/tft/origins/".$value['alias'];

            unset($value['seasonId']);
            unset($value['versionId']);
            unset($value['creater']);
            unset($value['createTime']);
            unset($value['updateMan']);
            unset($value['updateTime']);
            unset($value['isDelete']);
            unset($value['deleteMan']);
            unset($value['deleteTime']);
        }

        //职业
        $jobData = $this->db->table('tbjob')->where($where)->select();

        $jobFormat = [];
        foreach ($jobData as &$value) {
            $jobFormat[$value['jobId']] = $value['name'];
            $value['level'] = json_decode($value['level'], true);
            $value['imagePath'] = "https://game.gtimg.cn/images/lol/act/img/tft/classes/".$value['alias'];

            unset($value['seasonId']);
            unset($value['versionId']);
            unset($value['creater']);
            unset($value['createTime']);
            unset($value['updateMan']);
            unset($value['updateTime']);
            unset($value['isDelete']);
            unset($value['deleteMan']);
            unset($value['deleteTime']);
        }

        //英雄
        $heroData = $this->db->table('tbhero')->where($where)->select();

        $heroType = $this->db->table('tbherotype')->select();
        $type = [];
        foreach ($heroType as $value) {
            $type[$value['id']] = $value['name'];
        }

        $heroMini = $this->db->table('tbheromini')->select();
        $mini = [];
        foreach ($heroMini as $value) {
            $mini[$value['id']] = $value['name'];
        }
        $heroFormat = [];
        foreach ($heroData as &$value) {
            $heroFormat[$value['heroId']] = $value['name'];
            $value['type'] = $type[$value['typeId']];
            $value['mini'] = $mini[$value['miniId']];
            $value['imagePath'] =
                str_replace('upload/img/hero/', 'https://game.gtimg.cn/images/lol/act/img/tft/littlelegends/', $value['imagePath']);

            $value['shape'] = HeroModel::SHAPE_ARRAY[$value['shape']];
            $value['quality'] = HeroModel::QUALITY_ARRAY[$value['quality']];

            unset($value['seasonId']);
            unset($value['versionId']);
            unset($value['creater']);
            unset($value['createTime']);
            unset($value['updateMan']);
            unset($value['updateTime']);
            unset($value['isDelete']);
            unset($value['deleteMan']);
            unset($value['deleteTime']);
        }

        //棋子
        $chessData = $this->db->table('tbchess')->where($where)->select();
        foreach ($chessData as &$value) {
            $raceIdsArr = explode(',', $value['raceIds']);
            $raceIdsArr = $raceIdsArr ? $raceIdsArr : [];
            foreach ($raceIdsArr as $raceId) {
                $value['races'][] = $raceFormat[$raceId];
            }
            $value['races'] = implode(',', $value['races']);


            $jobIdsArr = explode(',', $value['jobIds']);
            $jobIdsArr = $jobIdsArr ? $jobIdsArr : [];
            foreach ($jobIdsArr as $jobId) {
                $value['jobs'][] = $jobFormat[$jobId];
            }
            $value['jobs'] = implode(',', $value['jobs']);


            //攻击力和生命值详情
            $value['attackData'] =  $value['attack'].'/'.$value['attack']*$value['attackMag'].'/'.$value['attack']*$value['attackMag']*$value['attackMag'];
            $value['lifeData'] =  $value['life'].'/'.$value['life']*$value['lifeMag'].'/'.$value['life']*$value['lifeMag']*$value['lifeMag'];


            $value['skillImage'] =
                str_replace('upload/img/skill/', 'https://game.gtimg.cn/images/lol/act/img/tft/champions/', $value['skillImage']);

            // "https://game.gtimg.cn/images/lol/act/img/tft/champions/".$value['skillImage'];

            $originalImageArr = array_filter(explode(",", $value['originalImage']));
            if (count($originalImageArr) > 1) {
                foreach ($originalImageArr as &$originalImage) {
                    $originalImage = str_replace('upload/img/original-image/', 'https://game.gtimg.cn/images/lol/act/img/tft/original-image/', $originalImage);
                }
                $value['originalImage'] = $originalImageArr;
            } else {
                $value['originalImage'] =
                    str_replace('upload/img/original-image/', 'https://game.gtimg.cn/images/lol/act/img/tft/original-image/', $value['originalImage']);
            }


            unset($value['seasonId']);
            unset($value['versionId']);
            unset($value['creater']);
            unset($value['createTime']);
            unset($value['updateMan']);
            unset($value['updateTime']);
            unset($value['isDelete']);
            unset($value['deleteMan']);
            unset($value['deleteTime']);
        }

        //道具
        $equipData = $this->db->table('tbequip')->where($where)->select();

        foreach ($equipData as &$value) {
            $value['imagePath'] = str_replace('upload/img/equip/', 'https://game.gtimg.cn/images/lol/act/img/tft/items/', $value['imagePath']);
//            $heroIdsArr = explode(',',$value['heroIds']);
//            $heroIdsArr = $heroIdsArr ? $heroIdsArr : [];
//            foreach ($heroIdsArr as $heroId) {
//                $value['heros'][] = $raceFormat[$heroId];
//            }
//            $value['heros'] = implode(',',$value['heros']);

            unset($value['seasonId']);
            unset($value['versionId']);
            unset($value['creater']);
            unset($value['createTime']);
            unset($value['updateMan']);
            unset($value['updateTime']);
            unset($value['isDelete']);
            unset($value['deleteMan']);
            unset($value['deleteTime']);
        }


        $jsonData = [
            'version'=>$versionNumber,
            'season'=>$seasonNumber,
            'time'=>date('Y-m-d H:i:s', time())
        ];
        $jsonData['data'] = $raceData;
        $resRace = file_put_contents($dir . 'race.js', json_encode($jsonData));


        $save['filename'] ='race.js';
        $save['url'] = '/'.$dir . 'race.js';
        $recordRace = $this->db->table('tbrecord')->insert($save);
        if ($recordRace) {
            logWrite(1, true, 'tbrecord', $dir.'race.js写入至tbRecord表成功');
        } else {
            logWrite(1, false, 'tbrecord', $dir.'race.js写入至tbRecord表失败');
        }


        if ($resRace) {
            logWrite(5, true, '', '生成race.js');
        } else {
            logWrite(5, false, '', '生成race.js');
            $this->ajaxError("生成失败");
        }


        $jsonData['data'] = $jobData;
        $resJob = file_put_contents($dir . 'job.js', json_encode($jsonData));

        $save['filename'] ='job.js';
        $save['url'] = '/'.$dir . 'job.js';
        $recordRace = $this->db->table('tbrecord')->insert($save);
        if ($recordRace) {
            logWrite(1, true, 'tbrecord', $dir.'job.js写入至tbRecord表成功');
        } else {
            logWrite(1, false, 'tbrecord', $dir.'job.js写入至tbRecord表失败');
        }

        if ($resJob) {
            logWrite(5, true, '', '生成job.js');
        } else {
            logWrite(5, false, '', '生成job.js');
            $this->ajaxError("生成失败");
        }

        $jsonData['data'] = $heroData;
        $resHero = file_put_contents($dir . 'hero.js', json_encode($jsonData));
        $save['filename'] ='hero.js';
        $save['url'] = '/'.$dir . 'hero.js';
        $recordRace = $this->db->table('tbrecord')->insert($save);
        if ($recordRace) {
            logWrite(1, true, 'tbrecord', $dir.'hero.js写入至tbRecord表成功');
        } else {
            logWrite(1, false, 'tbrecord', $dir.'hero.js写入至tbRecord表失败');
        }
        if ($resHero) {
            logWrite(5, true, '', '生成hero.js');
        } else {
            logWrite(5, false, '', '生成hero.js');
            $this->ajaxError("生成失败");
        }
        $jsonData['data'] = $chessData;
        $resChess = file_put_contents($dir . 'chess.js', json_encode($jsonData));

        $save['filename'] ='chess.js';
        $save['url'] = '/'.$dir . 'chess.js';
        $recordRace = $this->db->table('tbrecord')->insert($save);
        if ($recordRace) {
            logWrite(1, true, 'tbrecord', $dir.'chess.js写入至tbRecord表成功');
        } else {
            logWrite(1, false, 'tbrecord', $dir.'chess.js写入至tbRecord表失败');
        }
        if ($resChess) {
            logWrite(5, true, '', '生成chess.js');
        } else {
            logWrite(5, false, '', '生成chess.js');
            $this->ajaxError("生成失败");
        }
        $jsonData['data'] = $equipData;
        $resEquip = file_put_contents($dir . 'equip.js', json_encode($jsonData));

        $save['filename'] ='equip.js';
        $save['url'] = '/'.$dir . 'equip.js';
        $recordRace = $this->db->table('tbrecord')->insert($save);
        if ($recordRace) {
            logWrite(1, true, 'tbrecord', $dir.'equip.js写入至tbRecord表成功');
        } else {
            logWrite(1, false, 'tbrecord', $dir.'equip.js写入至tbRecord表失败');
        }
        if ($resEquip) {
            logWrite(5, true, '', '生成equip.js');
        } else {
            logWrite(5, false, '', '生成equip.js');
            $this->ajaxError("生成失败");
        }


        $this->ajaxSuccess("生成成功", []);
    }
    /**
     * 创建js文件保存目录
     * @param $versionNumber
     * @return bool|string
     */
    public function makeJsDir($versionNumber)
    {
        $savePath = 'upload/js/';

        //目录
        $dir = $versionNumber . '/';
        if (!is_dir($savePath . $dir)) {
            $res = mkdir($savePath . $dir, 0755, true);
            logWrite(parent::LOG_TYPE_OTHER, $res, '', '创建保存目录');
            if ($res) {
                return $savePath . $dir;
            }
            return false;
        }
        return $savePath . $dir;
    }


    public function versionAndSeason()
    {
        //获取版本集合数据
        $db = Lib\Db\DbModel::init(); // 构造方法，线上自动切换

        $versionInfo = $db->table('tbversion')->order('id', 'desc')->limit(10)->select();
        $seasonInfo = $db->table('tbseason')->order('id', 'desc')->limit(10)->select();

        foreach ($versionInfo as &$arr) {
            $arr['isCurrent'] = $arr['isCurrent'] == 1 ?"是":"否";
        }
        foreach ($seasonInfo as &$arr) {
            $arr['isCurrent'] = $arr['isCurrent'] == 1 ?"是":"否";
        }

        $this->assign('versionInfo', $versionInfo);
        $this->assign('seasonInfo', $seasonInfo);
        $this->display('Admin/Main/vands');
    }

    public function addVersionOrSeason()
    {
        $type = I('post.type');
        $number= I('post.number');

        if (!in_array($type, ['version','season'])) {
            $this->ajaxError('类型错误');
        }
        if (empty($number)) {
            $this->ajaxError('数据不能为空');
        }


        $time = date('Y-m-d H:i:s', time());
        $creater = $this->login->getLoginInfo()['name'];
        if ($type=='version') {
            $checkVersion = $this->versionModel->pregVersion($number);
            if ($checkVersion === false) {
                $this->ajaxError('不是一个正确的版本号');
            }

            //检查是否已经存在
            $resultVersion = $this->versionModel->getVersionByNum($number);

            if (!empty($resultVersion)) {
                $this->ajaxError('版本号已存在');
            }

            $res = $this->db->table('tbversion')->insert([
                'versionNumber'=>$number,
                'createTime'=>$time,
                'creater'=>$creater
            ]);
            logWrite(parent::LOG_TYPE_INSENT, $res, 'tbversion');
        } else {
            $checkSeason = $this->seasonModel->pregSeason($number);
            if ($checkSeason === false) {
                $this->ajaxError('不是一个正确的季度号');
            }

            //检查是否已经存在

            $resultSeason = $this->seasonModel->getSeasonByNum($number);

            if (!empty($resultSeason)) {
                $this->ajaxError('季度号已存在');
            }

            $res = $this->db->table('tbseason')->insert([
                'seasonNumber'=>$number,
                'createTime'=>$time,
                'creater'=>$creater
            ]);
            logWrite(parent::LOG_TYPE_INSENT, $res, 'tbseason');
        }

        if ($res) {
            $this->ajaxSuccess("添加成功");
        } else {
            $this->ajaxError('添加失败');
        }
    }
}
